package com.hmall.item.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Date;

@RestController
@RequestMapping("/item")
public class ItemController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IItemService itemService;
    @GetMapping("/list")
    public PageDTO list(Integer page,Integer size){
        IPage<Item> page1 = new Page<>(page, size);
        itemService.page(page1);
        return new PageDTO<Item>(page1.getTotal(),page1.getRecords());
    }
    @GetMapping("/{id}")
    public Item getById(@PathVariable Long id){
        return  itemService.getById(id);
    }
    @PostMapping
    public void save(@RequestBody Item item){
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        itemService.save(item);
    }
    @PutMapping("/status/{id}/{status}")
    public void underCarriage(@PathVariable Integer id,@PathVariable Integer status){
        Item item = itemService.getById(id);
        item.setStatus(status);
        itemService.updateById(item);
        String routingKey = status == 1 ? "item.up" : "item.down";
        rabbitTemplate.convertAndSend("item.topic", routingKey,id);
    }
    @PutMapping
    public void update(@RequestBody Item item){
        item.setUpdateTime(new Date());
        itemService.updateById(item);
    }
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Integer id){
        Item item = itemService.getById(id);
        if(item.getStatus()==1){
            throw new RuntimeException("该商品未下架，请先下架!");
        }
        itemService.removeById(id);
    }
    @PutMapping("/stock/{itemId}/{num}")
    public void updateStock(@PathVariable("itemId") Long itemId, @PathVariable("num") Integer num){
        itemService.deductStock(itemId, num);
    }
}
